<script setup>
import { onMounted, ref, watch } from 'vue';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import { uploadFile } from "@/apis/uploadFile"
import { message } from 'ant-design-vue';
const props = defineProps({
    maxNum: {
        type: Number,
        required: true,
        default: 4,
    },
    list: {
        type: [String, Array],
        required: true,
        default: 4,
    }
});
const emit = defineEmits(['upload', "delete"])
const loading = ref(false)
const fileList = ref([]);
const previewImage = ref('');
const previewVisible = ref(false);
const previewTitle = ref('');
watch(() => props.list, (newdata, old) => {
    fileList.value = [];
    if (props.list === "") return;
    let arr = props.list.split(",").filter(item => item !== "")
    arr.forEach((item, index) => {
        fileList.value.push({
            uid: index + 1,
            name: item,
            url: item,
        })
    })
}, { immediate: true, deep: true })
const beforeUpload = (file) => {
    loading.value = true
    uploadFile({ file: file }).then(res =>{
        if (res.code === 200){
            props.list?(emit('upload', props.list + "," + res.data)):(emit('upload',res.data))
            loading.value = false;
        } else {
            loading.value = false
        }
    })

    return false;
}
const handleCancel = () => {
    previewVisible.value = false;
    previewTitle.value = '';
};
const handlePreview = async file => {
    if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
    }
    previewImage.value = file.url || file.preview;
    previewVisible.value = true;
    previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};
const getBase64 = (file) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}
const handleDeleteImage = (file) => {
    let imgList = JSON.parse(JSON.stringify(fileList.value))
    let list = imgList.filter(item => item.uid !== file.uid)
    let str = "";
    list.forEach(item => {
        str += item.url + ","
    })
    emit("delete", str.slice(0, -1))
}
defineExpose({
    loading
})
</script>
<template>
    <a-upload :file-list="fileList" name="avatar" list-type="picture-card" class="avatar-uploader"
        :before-upload="beforeUpload" @preview="handlePreview" @remove="handleDeleteImage">
        <div v-if="fileList.length < maxNum">
            <loading-outlined v-if="loading"></loading-outlined>
            <plus-outlined v-else></plus-outlined>
            <div class="ant-upload-text">上传图片</div>
        </div>
    </a-upload>
    <a-modal :open="previewVisible" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
</template>
<style lang='' scoped>

</style>